import { IViewDetail, formatAppDERSPath, IParam } from '@/core';
import qs from 'qs';
import {
	getSessionStorage,
	isExistAndNotEmpty,
	notEmpty,
} from '../core/utils/util';

export function buildUpRoutePath(
	route: any,
	view: IViewDetail,
	context: any = {},
	args: any[],
	data: any
): string {
	const { appDERSPaths, parameters } = view;
	const deResParameters = formatAppDERSPath(context, appDERSPaths);
	const indexRoutePath = getIndexRoutePath(route);
	const deResRoutePath = getDeResRoutePath(context, deResParameters, args);
	const deRoutePath = getActiveRoutePath(parameters, args, data, context);
	return `${indexRoutePath}${deResRoutePath}${deRoutePath}`;
}

/**
 * 获取首页根路由路径
 *
 * @static
 * @param {Route} route 路由对象
 * @returns {string}
 * @memberof ViewTool
 */
export function getIndexRoutePath(route: any): string {
	const parameter = route.meta?.parameters?.[0] || {
		pathName: 'views',
		parameterName: 'view',
	};
	const { pathName, parameterName } = parameter;
	const param = route.params[parameterName];
	if (notEmpty(param)) {
		return `/${pathName}/${param}`;
	}
	return `/${parameterName}`;
}

/**
 * 获取关系实体路径
 *
 * @static
 * @param {*} [viewParam={}] 视图参数
 * @param {any[] | undefined} deResParameters 关系实体参数对象
 * @param {any[]} args 多项数据
 * @returns {string}
 * @memberof ViewTool
 */
export function getDeResRoutePath(
	context: any = {},
	deResParameters: any[] | undefined,
	args: any[]
): string {
	let routePath = '';
	let [arg] = args;
	arg = arg ? arg : {};
	if (deResParameters && deResParameters.length > 0) {
		deResParameters.forEach(
			({
				pathName,
				parameterName,
			}: {
				pathName: string;
				parameterName: string;
			}) => {
				let value: any = null;
				if (
					context[parameterName] &&
					!Object.is(context[parameterName], '') &&
					!Object.is(context[parameterName], 'null')
				) {
					value = context[parameterName];
				} else if (
					arg[parameterName] &&
					!Object.is(arg[parameterName], '') &&
					!Object.is(arg[parameterName], 'null')
				) {
					value = arg[parameterName];
				}
				routePath =
					`${routePath}/${pathName}` +
					(isExistAndNotEmpty(value)
						? `/${encodeURIComponent(`${value}`)}`
						: '');
			}
		);
	}
	return routePath;
}

export function getActiveRoutePath(
	parameters: any[] | undefined,
	args: any[],
	data: any,
	context: any = {}
): string {
	let routePath = '';
	// 不存在应用实体
	if (parameters && parameters.length > 0) {
		if (parameters.length === 1) {
			const [{ parameterName }] = parameters;
			routePath = `/views/${parameterName}`;
			if (Object.keys(data).length > 0) {
				routePath = `${routePath}?${qs.stringify(data, { delimiter: ';' })}`;
			}
		} else if (parameters.length === 2) {
			let [arg] = args;
			arg = arg ? arg : {};
			const [
				{ pathName: _pathName, parameterName: _parameterName },
				{ pathName: _pathName2, parameterName: _parameterName2 },
			] = parameters;
			const _value: any =
				arg[_parameterName] || context[_parameterName] || null;
			routePath = `/${_pathName}${
				isExistAndNotEmpty(_value) ? `/${encodeURIComponent(`${_value}`)}` : ''
			}/views/${_parameterName2}`;
			if (Object.keys(data).length > 0) {
				routePath = `${routePath}?${encodeURIComponent(
					`${qs.stringify(data, { delimiter: ';' })}`
				)}`;
			}
		}
	}
	return routePath;
}

/**
 * @description 处理视图参数
 * @export
 * @param {string} urlStr
 * @return {*}  {*}
 */
export function handleViewParam(urlStr: string): any {
	const tempViewParam: any = {};
	const tempViewparam: any = urlStr.slice(urlStr.indexOf('?') + 1);
	const viewparamArray: Array<string> =
		decodeURIComponent(tempViewparam).split(';');
	if (viewparamArray.length > 0) {
		viewparamArray.forEach((item: any) => {
			if (item.startsWith('srfdcsystem=') && item.indexOf('#') !== -1) {
				item = item.substring(0, item.indexOf('#'));
			}
			Object.assign(tempViewParam, qs.parse(item));
		});
	}
	return tempViewParam;
}

/**
 * @description 获取包含DcSystemId的视图参数
 * @export
 * @return {*}
 */
export function getDcSystemIdViewParam() {
	let tempViewParam = handleViewParam(window.location.href);
	if (!tempViewParam.srfdcsystem) {
		if (!tempViewParam.redirect) {
			if (getSessionStorage('dcsystem')) {
				tempViewParam = getSessionStorage('dcsystem');
			}
		} else {
			tempViewParam = handleViewParam(tempViewParam.redirect);
		}
	}
	const dcSystemId = App.getProjectSetting().dcSystemId;
	if (!tempViewParam.srfdcsystem && dcSystemId) {
		Object.assign(tempViewParam, { srfdcsystem: dcSystemId });
	}
	return tempViewParam;
}

/**
 * 格式化路由参数
 *
 * @export
 * @param {*} params
 * @param {*} fullPath
 * @param {*} context
 * @param {*} viewparams
 */
export function formatRouteParams(
	params: any,
	fullPath: string,
	context: any,
	viewparams: any
): void {
	Object.keys(params).forEach((key: string, index: number) => {
		const param: string | null | undefined = params[key];
		if (!param || Object.is(param, '') || Object.is(param, 'null')) {
			return;
		}
		if (param.indexOf('=') > 0) {
			const _param = qs.parse(param, { delimiter: ';' });
			Object.assign(context, _param);
		} else {
			Object.assign(context, { [key]: param });
		}
	});
	if (fullPath && fullPath.indexOf('?') > -1) {
		const _viewparams: any = fullPath.slice(fullPath.indexOf('?') + 1);
		const _viewparamArray: Array<string> =
			decodeURIComponent(_viewparams).split(';');
		if (_viewparamArray.length > 0) {
			_viewparamArray.forEach((item: any) => {
				const result = qs.parse(item);
				if (Object.keys(result) && Object.keys(result).length > 0) {
					Object.keys(result).forEach((key: any) => {
						if (
							!result[key] ||
							Object.is(result[key], '') ||
							Object.is(result[key], 'null')
						) {
							Object.assign(viewparams, { [key]: null });
						} else {
							Object.assign(viewparams, { [key]: result[key] });
						}
					});
				}
			});
		}
	}
}

/**
 * 安装Vue组件
 * @param main
 * @param extra
 * @returns
 */
export const withInstall = <T, E extends Record<string, any>>(
	main: T,
	extra?: E
) => {
	if (extra) {
		for (const [key, comp] of Object.entries(extra)) {
			(main as any)[key] = comp;
		}
	}
	return main as any;
};

/**
 * 不改变原数组引用为数组全量赋值（避免取消掉vue3的响应式）
 *
 * @export
 * @param {any[]} target 目标数据
 * @param {any[]} value 值
 */
export function setArray(target: any[], value: any[]) {
	target.length === 0;
	target.push(...value);
}

/**
 * 转化表单重复器值（vo<===>dto）
 *
 * @export
 * @param {string} field 重复器属性
 * @param {IParam} model 表单模型
 * @param {boolean} isReverse 是否反向 正向：map<codeName,valueItem> 反向：map<valueItem, codeName>
 * @param {IParam[]} [source=[]] 原始值
 * @return {*} 
 */
export function transformValue(
	field: string,
	model: IParam,
	isReverse: boolean,
	source: IParam[] = []
) {
	const returnValues: IParam[] = [];
	const tempMap: Map<string, string> = new Map();
	const sourceModel = Object.values(model.detailModel);
	const repeaterModels = sourceModel.filter((item: any) => {
		return item.parentIsRepeater === true && item.parentCodeName === field;
	});
	if (repeaterModels && repeaterModels.length > 0) {
		repeaterModels.forEach((element: any) => {
			if (element.valueItem) {
				if (isReverse) {
					tempMap.set(element.valueItem, element.codeName);
				} else {
					tempMap.set(element.codeName, element.valueItem);
				}
			} else {
				tempMap.set(element.codeName, element.codeName);
			}
		});
	}
	if (source && source.length > 0) {
		source.forEach((data: IParam) => {
			let tempItem: IParam = {};
			if (data && Object.keys(data).length > 0) {
				Object.keys(data).forEach((field: string) => {
					if (tempMap.has(field)) {
						const key: string = tempMap.get(field) as string;
						tempItem[key] = data[field];
					} else {
						tempItem[field] = data[field];
					}
				});
			}
			returnValues.push(tempItem);
		});
	}
	return returnValues;
}
